﻿using DncLite.Domain.Core.Bus;
using DncLite.Domain.Core.Commands;
using DncLite.Domain.Interfaces;
using Microsoft.Extensions.Caching.Memory;
using System.Collections.Generic;
using System.Linq;

namespace DncLite.Domain.CommandHandlers
{
    public class CommandHandler
    {
        private readonly IUnitOfWork _uow;
        private readonly IMediatorHandler _bus;
        private IMemoryCache _cache;

        public CommandHandler(IUnitOfWork uow
            , IMediatorHandler bus
            , IMemoryCache cache)
        {
            _uow = uow;
            _bus = bus;
            _cache = cache;
        }

        protected void NotifyValidationErrors(Command message)
        {
            var errorInfo = new List<string>();
            errorInfo.AddRange(message.ValidationResult.Errors.Select(x => x.ErrorMessage));
            if (errorInfo.Count > 0)
            {
                _cache.Set("ErrorData", errorInfo);
            }
        }

        public bool Commit()
        {
            if (_uow.Commit())
            {
                return true;
            }
            return false;
        }
    }
}
